<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/8/29
 * Time: 16:21
 */

namespace app\admin\controller;


use app\admin\validate\GoodAddValidate;

use app\model\Goods as GoodsModel;
class Goods extends BaseController
{
    /*
     * 商品列表展示
     */
    public function showlist()
    {
        //通过模型查询Goods数据表数据，显示在列表页面
        $goods = new GoodsModel();
        $list = $goods->paginate(5);
        // 模板变量赋值
        $this->assign('list', $list);
        // 模板渲染
        return $this->fetch();
    }
    /*
     * 商品表内容添加
     */
    public function add()
    {
        //一个页面处理两个业务逻辑：展示页面，表单提交
        //表单提交
        //1 获取表单数据
        $data = input('post.');
        if(!empty($data)){
        //2 处理logo图片上传
            $file = request()->file('goods_logo');
            $fileName = $this->upload($file);
            $data['goods_logo'] = $fileName;
        //3 模型中验证表单字段 并写入数据库 goods表
            $res =  (new GoodsModel())->store($data);
        //4 判断写入是否成功
                if($res['code'] == 1){
                    $this->success($res['msg'],'goods/showlist');
                }else{
                    $error = $res['msg'];
                    $this->assign('error',$error);
                    return $this->fetch();
                }
        }else{
        // 展示表单页面
            return $this->fetch();
        }
    }
    public function edit($id)
    {
        //一个页面处理两个业务逻辑：展示页面，表单提交
        //表单提交
        //1 获取表单数据
        $data = input('post.');
        if(!empty($data)){
            //2 处理logo图片上传
            $file = request()->file('goods_logo');
            $fileName = $this->upload($file);
            $data['goods_logo'] = $fileName;
            //3 模型中验证表单字段 并写入数据库 goods表
            $res =  (new GoodsModel())->where('id','=',$id)->update($data);

            //4 判断写入是否成功
            if($res){
                $this->success("修改成功",'goods/showlist');
            }else{
//                $error = $res['msg'];
                $this->assign('修改失败','goods/showlist');
                return $this->fetch();
            }
        }else{
            // 查询原数据并展示表单页面
            $data = GoodsModel::get($id)->toArray();
            $this->assign('data',$data);
            return $this->fetch();
        }

    }
    public function del($id)
    {
       $res = GoodsModel::where('id','=',$id)->delete();
        if($res){
            $this->success('商品删除成功','goods/showlist');
        }else{
            $this->error('商品删除失败','goods/showlist');
        }
    }

}